<template>
	<view class="custom-upload">
		<!-- 预览图片 -->
		<template v-if="previewImage"></template>

		<!-- 如果图片数量在设定范围内 -->
		<template v-if="isInCount">
			<view class="upload-button" @tap="chooseOperationType" :style="[{width: '200rpx',height: '200rpx'}]">
				<u-icon name="plus" size="26" color="#2979ff"></u-icon>
				<text v-if="uploadText" class="upload-button-text">{{ uploadText }}</text>
				<text v-else class="upload-button-text">上传</text>
			</view>
		</template>

		<!-- 选项弹出层 -->
		<u-popup :show="showOptionsPopup" :round="10" mode="bottom" :closeable="true" @close="this.showOptionsPopup=false">
			<view class="option-list">
				<view class="option-btn" @tap="onTakePhoto">拍照</view>
				<view class="option-btn" @tap="onChoosePhoto">从相册选择</view>
				<view class="option-btn-close" @tap="this.showOptionsPopup=false">取消</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
	export default {
		name: "customUpload",
		props: {
			// 上传图标的文字
			uploadText: {
				type: String,
				default: ''
			},
		},
		data() {
			return {
				previewImage: false, // 预览图片
				isInCount: true, // 是在限制的文件数量范围内
				showOptionsPopup: false, // 选项弹出层
			};
		},
		methods: {
			// 选择操作类型
			chooseOperationType() {
				this.showOptionsPopup = true;
			},
			// 拍照
			onTakePhoto() {
				this.showOptionsPopup = false;
				uni.chooseMedia({
					count: 9,
					mediaType: ['image', 'video'],
					sourceType: ['album', 'camera'],
					maxDuration: 30,
					camera: 'back',
					success(res) {
						console.log(res.tempFiles)
					}
				})
			},
			//从文件夹选择
			onChoosePhoto() {
				this.showOptionsPopup = false;
			},
		}
	}
</script>

<style lang="scss">
	.custom-upload {
		border: 1px dashed red;
		display: flex;
		flex-direction: row;
		flex-wrap: wrap;

		.upload-button {
			padding: 10rpx;
			display: flex;
			flex-direction: column;
			justify-content: center;
			align-items: center;

			background-color: #f4f5f7;
			border-radius: 2px;
			margin: 0 8px 8px 0;
			box-sizing: border-box;

			.upload-button-text {
				margin-top: 8rpx;
				color: #ccc;
			}
		}

		.option-list {
			display: flex;
			flex-direction: column;
			justify-content: center;
			align-items: center;
			padding: 40rpx 40rpx 20rpx 40rpx;

			.option-btn {
				border-bottom: 1px solid #ccc6;
				padding: 30rpx;
				width: 100%;
				text-align: center;
				font-size: 16px;
			}

			.option-btn-close {
				padding: 30rpx;
				width: 100%;
				text-align: center;
				font-size: 16px;
			}
		}
	}
</style>